<template>
  <div class="work-log-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-info">
          <h1 class="page-title">
            <el-icon><Document /></el-icon>
            工作日志
          </h1>
          <p class="page-description">记录每日工作内容与思考</p>
        </div>
        <div class="header-stats">
          <div class="stat-item">
            <span class="stat-value">{{ dataList?.length || 0 }}</span>
            <span class="stat-label">总日志</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 工具栏 -->
    <div class="toolbar-section">
      <div class="toolbar-content">
        <div class="toolbar-left">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            @change="getDataList"
            class="date-range-picker"
          />
        </div>
        <div class="toolbar-right">
          <el-button :icon="Refresh" @click="refreshData" title="刷新数据">刷新</el-button>
          <el-button :icon="Upload" @click="batchAdd" title="导入数据">导入</el-button>
          <el-button :icon="Download" @click="downloadFile" title="导出数据">导出</el-button>
          <el-button :icon="Plus" type="primary" @click="openDrawer('新增', {})"> 新增日志 </el-button>
        </div>
      </div>
    </div>

    <!-- 日志列表 -->
    <div class="logs-grid">
      <div v-for="(item, index) in dataList" :key="index" class="log-card" @click="openView(item)">
        <div class="log-header">
          <div class="log-title">
            <span class="title-text">{{ formatDate(item.workDate) }} 工作日志</span>
          </div>
          <el-dropdown trigger="click" @command="handleCommand" @click.stop>
            <el-button circle size="small" text class="more-btn" @click.stop>
              <el-icon><More /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item :command="{ name: 'edit', item: item }">
                  <el-icon><Edit /></el-icon>
                  编辑
                </el-dropdown-item>
                <el-dropdown-item :command="{ name: 'delete', item: item }">
                  <el-icon><Delete /></el-icon>
                  删除
                </el-dropdown-item>
                <el-dropdown-item :command="{ name: 'view', item: item }">
                  <el-icon><View /></el-icon>
                  查看
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>

        <div class="log-content">
          <div class="log-summary">
            <h3>工作内容</h3>
            <p>{{ item.summary }}</p>
          </div>
          <div class="log-think">
            <h3>工作思考</h3>
            <p>{{ item.think }}</p>
          </div>
        </div>

        <div class="log-footer">
          <div class="log-meta">
            <el-icon><User /></el-icon>
            <span>{{ userNameRender(item.create_user, userList) }}</span>
          </div>
          <div class="log-meta">
            <el-icon><Clock /></el-icon>
            <span>{{ useDateFormat(item.create_at, "MM-DD HH:mm").value }}</span>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="!dataList || dataList.length === 0" class="empty-state">
        <el-empty description="暂无日志">
          <el-button type="primary" @click="openDrawer('新增', {})"> 创建第一条日志 </el-button>
        </el-empty>
      </div>
    </div>

    <el-backtop :right="100" :bottom="100" />

    <!-- 日志抽屉 -->
    <WorkLogDrawer ref="drawerRef" />

    <!-- 查看日志弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :destroy-on-close="true"
      width="70%"
      top="5vh"
      :title="logTitle"
      class="log-dialog"
    >
      <div class="log-view-content">
        <div class="log-view-header">
          <div class="log-view-date">{{ formatDate(curLog?.workDate || "") }} 工作日志</div>
          <div class="log-view-meta">
            <span>
              <el-icon><User /></el-icon> {{ userNameRender(curLog?.create_user, userList) }}
            </span>
            <span>
              <el-icon><Clock /></el-icon> {{ useDateFormat(curLog?.create_at, "YYYY-MM-DD HH:mm").value }}
            </span>
          </div>
        </div>

        <div class="log-view-section">
          <h3>工作内容</h3>
          <div class="log-view-text">{{ curLog?.summary }}</div>
        </div>

        <div class="log-view-section">
          <h3>工作思考</h3>
          <div class="log-view-text">{{ curLog?.think }}</div>
        </div>
      </div>
      <template #footer>
        <el-button @click="dialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 导入组件 -->
    <ImportExcel ref="dialogRef" />
  </div>
</template>

<script setup lang="tsx" name="workLog">
import { computed, onMounted, ref } from "vue";
import { Plus, More, User, Document, Clock, Edit, Delete, View, Refresh, Download, Upload } from "@element-plus/icons-vue";
import { useDateFormat } from "@vueuse/core";
import WorkLogDrawer from "./workLogDrawer.vue";
import ImportExcel from "@/components/ImportExcel/index.vue";
import { WorkLog } from "@/api/types/base";
import apiService from "@/api/services/apiService";
import { useHandleData } from "@/hooks/useHandleData";
import { useDataStore } from "@/stores/modules/data";
import { userNameRender } from "@/hooks/useTextRender";
import { ElMessage, ElMessageBox } from "element-plus";
import { useDownload } from "@/hooks/useDownload";
import { ExportColType } from "@/enums/sysEnum";

// 获取本周日期范围
const getWeekRange = () => {
  const now = new Date();
  const dayOfWeek = now.getDay(); // 0表示周日，1表示周一，...，6表示周六
  const startOfWeek = new Date(now);
  const endOfWeek = new Date(now);

  // 计算本周开始日期（周一）
  startOfWeek.setDate(now.getDate() - (dayOfWeek === 0 ? 6 : dayOfWeek - 1));

  // 计算本周结束日期（周日）
  endOfWeek.setDate(now.getDate() + (dayOfWeek === 0 ? 0 : 7 - dayOfWeek));

  // 格式化为 YYYY-MM-DD
  const formatDate = (date: Date) => {
    return date.toISOString().slice(0, 10);
  };

  return [formatDate(startOfWeek), formatDate(endOfWeek)] as [string, string];
};

const dataStore = useDataStore();
const dialogVisible = ref(false);
const logTitle = ref("");
const curLog = ref<WorkLog>();
const dateRange = ref<[string, string]>(getWeekRange());
const userList = computed(() => dataStore.userList);

const drawerRef = ref<InstanceType<typeof WorkLogDrawer> | null>(null);
const dialogRef = ref<InstanceType<typeof ImportExcel> | null>(null);

onMounted(() => {
  dataStore.findUserList();
  getDataList();
});

const dataList = ref<WorkLog[]>();

const getDataList = async () => {
  const condition: any = {};

  // 添加日期范围条件
  if (dateRange.value && dateRange.value[0] && dateRange.value[1]) {
    condition.workDate = {
      $gte: dateRange.value[0],
      $lte: dateRange.value[1]
    };
  }

  const options = {
    sort: {
      workDate: -1,
      create_at: -1
    }
  };

  let { data } = await apiService.find<WorkLog[]>("workLog", condition, options);
  dataList.value = data;
};

const handleCommand = command => {
  if (command.name === "edit") {
    openDrawer("编辑", command.item);
  } else if (command.name === "delete") {
    deleteLog(command.item);
  } else if (command.name === "view") {
    openView(command.item);
  }
};

const openView = async item => {
  curLog.value = item;
  logTitle.value = `${formatDate(item.workDate)} 工作日志`;
  dialogVisible.value = true;
};

// 刷新数据
const refreshData = async () => {
  try {
    // 重新加载用户列表和日志数据
    await dataStore.findUserList();
    await getDataList();
    ElMessage.success("数据刷新成功");
  } catch (error) {
    console.error("刷新数据失败:", error);
    ElMessage.error("数据刷新失败");
  }
};

// 删除日志
const deleteLog = async (params: WorkLog) => {
  await useHandleData(apiService.deleteById, "workLog", params._id, `删除工作日志【${formatDate(params.workDate)}】`);
  getDataList();
};

// 打开 drawer(新增、查看、编辑)
const openDrawer = (title: string, row: Partial<WorkLog> = {}) => {
  const params = {
    title,
    tbName: "workLog",
    isView: title === "查看",
    row: row,
    api: title.indexOf("新增") !== -1 ? apiService.save : title === "编辑" ? apiService.updateById : undefined,
    getTableList: getDataList
  };
  drawerRef.value?.acceptParams(params);
};

// 格式化日期
const formatDate = (dateStr: string) => {
  if (!dateStr) return "";
  const date = new Date(dateStr);
  return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`;
};

// 导出数据
const downloadFile = async () => {
  ElMessageBox.confirm("确认导出数据?", "温馨提示", { type: "warning" }).then(() =>
    useDownload(apiService.commonExport, `工作日志-${useDateFormat(new Date(), "YYYY-MM-DD").value}`, "", getExcelConfig(), false)
  );
};

// 导入数据
const batchAdd = () => {
  const params = {
    title: "工作日志",
    defaultTip: "日志日期相同则跳过",
    coverTip: "日志日期相同则覆盖",
    tempUrl: "/template/workLog",
    getTableList: getDataList,
    importApi: apiService.commonImport,
    config: getExcelConfig()
  };
  dialogRef.value?.acceptParams(params);
};

const getExcelConfig = (): any => {
  return {
    params: {},
    tableName: "workLog",
    keyPropName: "workDate",
    enumTypes: [],
    tableConfigs: [{ tableName: "users", fields: ["_id", "userName"] }],
    header: [
      { header: "序号", width: 6, ext: { prop: "index", type: ExportColType.INDEX } },
      { header: "工作日期", width: 15, ext: { prop: "workDate", type: ExportColType.DEFAULT } },
      { header: "工作总结", width: 40, ext: { prop: "summary", type: ExportColType.DEFAULT } },
      { header: "工作思考", width: 40, ext: { prop: "think", type: ExportColType.DEFAULT } },
      {
        header: "创建人",
        width: 15,
        ext: { prop: "create_user", type: ExportColType.TABLE, key: "users", label: "userName", value: "_id" }
      },
      { header: "创建时间", width: 20, ext: { prop: "create_at", type: ExportColType.DATE } }
    ]
  };
};
</script>

<style lang="scss" scoped>
.work-log-page {
  min-height: 100vh;
  padding: 10px;
  background: var(--el-bg-color-page);
}

// 页面头部
.page-header {
  position: relative;
  padding: 30px;
  margin-bottom: 24px;
  overflow: hidden;
  color: white;
  background: linear-gradient(135deg, var(--el-color-primary) 0%, var(--el-color-primary-light-3) 100%);
  border-radius: 12px;
  .header-content {
    position: relative;
    z-index: 2;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .header-info {
      .page-title {
        display: flex;
        gap: 12px;
        align-items: center;
        margin: 0 0 8px;
        font-size: 28px;
        font-weight: 600;
        color: white;
        .el-icon {
          font-size: 32px;
        }
      }
      .page-description {
        margin: 0;
        font-size: 16px;
        color: rgb(255 255 255 / 80%);
      }
    }
    .header-stats {
      display: flex;
      gap: 30px;
      .stat-item {
        text-align: center;
        .stat-value {
          display: block;
          font-size: 24px;
          font-weight: 700;
          color: white;
        }
        .stat-label {
          display: block;
          margin-top: 4px;
          font-size: 14px;
          color: rgb(255 255 255 / 80%);
        }
      }
    }
  }
}

// 工具栏
.toolbar-section {
  margin-bottom: 24px;
  .toolbar-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20px;
    background-color: var(--el-bg-color);
    border: 1px solid var(--el-border-color-lighter);
    border-radius: 12px;
    box-shadow: 0 2px 12px rgb(0 0 0 / 10%);
    .toolbar-left {
      display: flex;
      gap: 16px;
      align-items: center;
      .date-range-picker {
        width: 300px;
      }
    }
    .toolbar-right {
      display: flex;
      align-items: center;
    }
  }
}

// 日志网格
.logs-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 20px;
  .log-card {
    position: relative;
    padding: 20px;
    cursor: pointer;
    background-color: var(--el-bg-color);
    border: 1px solid var(--el-border-color-lighter);
    border-radius: 12px;
    box-shadow: 0 2px 12px rgb(0 0 0 / 10%);
    transition: all 0.3s ease;
    &:hover {
      border-color: var(--el-color-primary-light-7);
      box-shadow: 0 4px 20px rgb(0 0 0 / 15%);
      transform: translateY(-2px);
    }
    .log-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 16px;
      .log-title {
        display: flex;
        flex: 1;
        gap: 8px;
        align-items: center;
        min-width: 0;
        .title-text {
          overflow: hidden;
          font-size: 16px;
          font-weight: 600;
          color: var(--el-text-color-primary);
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
      .more-btn {
        color: var(--el-text-color-placeholder);
        &:hover {
          color: var(--el-color-primary);
        }
      }
    }
    .log-content {
      margin-bottom: 16px;
      .log-summary,
      .log-think {
        margin-bottom: 16px;
        h3 {
          margin: 0 0 8px;
          font-size: 14px;
          font-weight: 600;
          color: var(--el-text-color-primary);
        }
        p {
          display: -webkit-box;
          margin: 0;
          overflow: hidden;
          font-size: 13px;
          line-height: 1.5;
          color: var(--el-text-color-regular);
          -webkit-line-clamp: 3;
          -webkit-box-orient: vertical;
        }
      }
    }
    .log-footer {
      display: flex;
      gap: 16px;
      align-items: center;
      padding-top: 12px;
      border-top: 1px solid var(--el-border-color-lighter);
      .log-meta {
        display: flex;
        gap: 6px;
        align-items: center;
        font-size: 12px;
        color: var(--el-text-color-regular);
        .el-icon {
          font-size: 14px;
          color: var(--el-color-primary);
        }
      }
    }
  }
}

// 空状态
.empty-state {
  grid-column: 1 / -1;
  padding: 60px 20px;
  text-align: center;
}

// 弹窗样式
.log-dialog {
  .log-view-content {
    max-height: 70vh;
    padding: 20px;
    overflow-y: auto;
    background: var(--el-bg-color-page);
    border-radius: 8px;
    .log-view-header {
      padding-bottom: 16px;
      margin-bottom: 24px;
      border-bottom: 1px solid var(--el-border-color-lighter);
      .log-view-date {
        margin-bottom: 12px;
        font-size: 20px;
        font-weight: 600;
        color: var(--el-text-color-primary);
      }
      .log-view-meta {
        display: flex;
        gap: 20px;
        span {
          display: flex;
          gap: 6px;
          align-items: center;
          font-size: 14px;
          color: var(--el-text-color-regular);
          .el-icon {
            color: var(--el-color-primary);
          }
        }
      }
    }
    .log-view-section {
      margin-bottom: 24px;
      h3 {
        margin: 0 0 12px;
        font-size: 16px;
        font-weight: 600;
        color: var(--el-text-color-primary);
      }
      .log-view-text {
        padding: 12px 16px;
        line-height: 1.6;
        color: var(--el-text-color-regular);
        white-space: pre-wrap;
        background: var(--el-bg-color);
        border-radius: 6px;
      }
    }
  }
}

// 响应式设计
@media (width <= 768px) {
  .work-log-page {
    padding: 16px;
  }
  .page-header {
    padding: 20px;
    .header-content {
      flex-direction: column;
      gap: 20px;
      text-align: center;
      .header-stats {
        justify-content: center;
      }
    }
  }
  .toolbar-content {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
    .toolbar-left {
      flex-direction: column;
      gap: 12px;
      .date-range-picker {
        width: 100%;
      }
    }
  }
  .logs-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }
}

@media (width <= 480px) {
  .logs-grid {
    .log-card {
      padding: 16px;
      .log-content .log-stats .stat-row {
        flex-direction: column;
        gap: 8px;
        align-items: flex-start;
      }
    }
  }
}
</style>
